package com.zhuhjay.c2;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.nio.charset.StandardCharsets;

/**
 * @author ZhuHJay
 * @date 2023/3/5 23:15
 */
public class LengthFieldDecoderTest {
    public static void main(String[] args) {
        EmbeddedChannel channel = new EmbeddedChannel(
                new LengthFieldBasedFrameDecoder(
                        1024, 0, 4, 0, 0),
                new LoggingHandler(LogLevel.DEBUG)
        );
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(1024);
        write2Buf(buffer, "Hello, World");
        write2Buf(buffer, "My name is zhangsan");
        // 发送数据
        channel.writeInbound(buffer);
    }

    /** 写入数据到 ByteBuf 中 */
    private static void write2Buf(ByteBuf buffer, String message) {
        buffer.writeInt(message.length());
        buffer.writeBytes(message.getBytes(StandardCharsets.UTF_8));
    }
}
